package com.zdp.dubbo.simulate.framework;

import com.zdp.dubbo.simulate.framework.protocol.http.HttpClient;
import com.zdp.dubbo.simulate.framework.register.RemoteMapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author ZhengDp
 * @Date 2023/6/4 12:30
 */
public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass) {
        // 获取用户的配置 jdk cglib

        Object o = Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getName(),method.getName(),method.getParameterTypes(),args,"1");
                HttpClient httpClient = new HttpClient();
                List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());
                // 负载均衡处理
                URL url =  LoadBalance.random(urls);
                Protocol protocol = ProtocolFactory.getProtocol();
                return protocol.send(url,invocation);
            }
        });

        return (T) o;
    }

}
